package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenjun
 * @date 2021/8/10
 */
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    @Autowired
    private  RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //缓存开关效验
        if (!enable) {
            return true;
        }

        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return  true;
        }

        //判断是否是get请求
        if (!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return  true;
        }

        //缓存
        String redisKey=createRedisKey(request);
        String data = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(data)) {
            //未命中
            return true;
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().println(data);

        return false;
    }

    /**
     * 生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
     *
     * @param request
     * @return java.lang.String
     * @date 2021/8/10
     */
    public static String createRedisKey(HttpServletRequest request) throws JsonProcessingException {
        String url =request.getRequestURI();
        ObjectMapper objectMapper = new ObjectMapper();
        String param = objectMapper.writeValueAsString(request.getParameterMap());
        String token = request.getHeader("Authorization");
        return "SERVER_CACHE_DATA_"+ DigestUtils.md5Hex(url+"_"+param+"_"+token);
    }
}
